using System.Diagnostics;
using System.IO;
using CaipuGuanliXitong.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;

namespace CaipuGuanliXitong.Controllers;

public class CookBookController : Controller
{
    private readonly CookBookDbContext _context;

    public CookBookController(CookBookDbContext context)
    {
        _context = context;
    }

    // GET: CookBook/GetAllCookBooks
    [HttpGet]
    [AllowAnonymous]
    public IActionResult GetAllCookBooks()
    {
        var cookBooks = _context.CookBooks.GetList().Where(x => !x.IsDeleted).ToList();
        var cookBookDtos = cookBooks.Select(c => new {
            id = c.Id,
            name = c.Name
        }).ToList();
        
        return Json(cookBookDtos);
    }
    
    // GET: CookBook
    public async Task<IActionResult> Index(string searchString, string sortOrder, int page = 1)
    {
        const int pageSize = 50;
        
        ViewBag.CurrentSort = sortOrder;
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
        ViewBag.CategorySortParm = sortOrder == "Category" ? "category_desc" : "Category";
        
        var query = _context.CookBooks.AsQueryable().Where(x => !x.IsDeleted);
        
        if (!String.IsNullOrEmpty(searchString))
        {
            query = query.Where(x => x.Name.Contains(searchString));
            ViewBag.CurrentFilter = searchString;
        }
        
        switch (sortOrder)
        {
            case "name_desc":
                query = query.OrderByDescending(x => x.Name);
                break;
            case "Date":
                query = query.OrderBy(x => x.CreatedTime);
                break;
            case "date_desc":
                query = query.OrderByDescending(x => x.CreatedTime);
                break;
            case "Category":
                query = query.OrderBy(x => x.Category);
                break;
            case "category_desc":
                query = query.OrderByDescending(x => x.Category);
                break;
            default:
                query = query.OrderBy(x => x.Name);
                break;
        }
        
        var totalItems = await query.CountAsync();
        var cookBooks = await query.ToPageListAsync(page, pageSize);
        
        ViewBag.TotalItems = totalItems;
        ViewBag.CurrentPage = page;
        ViewBag.PageSize = pageSize;
        
        return View(cookBooks);
    }

    // GET: CookBook/Details/5
    public IActionResult Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var cookBook = _context.CookBooks.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == id.Value);
        if (cookBook == null)
        {
            return NotFound();
        }

        return View(cookBook);
    }

    // GET: CookBook/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: CookBook/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create([Bind("Name,Category")] CookBook cookBook)
    {
        if (ModelState.IsValid)
        {
            cookBook.CreatedTime = DateTime.Now;
            cookBook.UpdatedTime = DateTime.Now;
            _context.CookBooks.Insert(cookBook);
            return RedirectToAction(nameof(Index));
        }
        return View(cookBook);
    }

    // GET: CookBook/Edit/5
    public IActionResult Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var cookBook = _context.CookBooks.AsQueryable().First(x => x.Id == id.Value);
        if (cookBook == null)
        {
            return NotFound();
        }
        return View(cookBook);
    }

    // POST: CookBook/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Edit(int id, [Bind("Id,Name,Category,CreatedTime")] CookBook cookBook)
    {
        if (id != cookBook.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            cookBook.UpdatedTime = DateTime.Now;
            _context.CookBooks.Update(cookBook);
            return RedirectToAction(nameof(Index));
        }
        return View(cookBook);
    }

    // GET: CookBook/Delete/5
    public IActionResult Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var cookBook = _context.CookBooks.AsQueryable().First(x => x.Id == id.Value);
        if (cookBook == null)
        {
            return NotFound();
        }

        return View(cookBook);
    }

    // POST: CookBook/Delete/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteConfirmed(int id)
    {
        var cookBook = _context.CookBooks.AsQueryable().First(x => x.Id == id);
        cookBook.IsDeleted = true;
        cookBook.UpdatedTime = DateTime.Now;
        _context.CookBooks.Update(cookBook);
        return RedirectToAction(nameof(Index));
    }
    
    // POST: CookBook/BatchDelete
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult BatchDelete(int[]? ids)
    {
        if (ids == null || ids.Length == 0)
        {
            ViewBag.Message = "未选择任何菜谱";
            ViewBag.IsSuccess = false;
        }
        else
        {
            try
            {
                var selectedCookBooks = _context.CookBooks.AsQueryable().Where(x => ids.Contains(x.Id)).ToList();
                foreach (var cookBook in selectedCookBooks)
                {
                    cookBook.IsDeleted = true;
                    cookBook.UpdatedTime = DateTime.Now;
                }
                _context.CookBooks.UpdateRange(selectedCookBooks);
                ViewBag.Message = $"成功删除 {ids.Length} 个菜谱";
                ViewBag.IsSuccess = true;
            }
            catch (Exception ex)
            {
                ViewBag.Message = "删除失败: " + ex.Message;
                ViewBag.IsSuccess = false;
            }
        }
        
        // 重新加载数据
        const int pageSize = 10;
        var query = _context.CookBooks.AsQueryable().Where(x => !x.IsDeleted);
        var totalItems = query.Count();
        var cookBooks = query.ToPageList(1, pageSize);
        
        ViewBag.TotalItems = totalItems;
        ViewBag.CurrentPage = 1;
        ViewBag.PageSize = pageSize;
        
        return View("Index", cookBooks);
    }
    
    // GET: CookBook/Export
    public IActionResult ExportToExcel()
    {
        var cookBooks = _context.CookBooks.GetList();
        
        // 创建工作簿
        var workbook = new XSSFWorkbook();
        var sheet = workbook.CreateSheet("菜谱数据");
        
        // 创建表头
        var headerRow = sheet.CreateRow(0);
        headerRow.CreateCell(0).SetCellValue("编号");
        headerRow.CreateCell(1).SetCellValue("菜谱名称");
        headerRow.CreateCell(2).SetCellValue("分类");
        headerRow.CreateCell(3).SetCellValue("创建时间");
        headerRow.CreateCell(4).SetCellValue("修改时间");
        
        // 填充数据
        for (int i = 0; i < cookBooks.Count; i++)
        {
            var row = sheet.CreateRow(i + 1);
            var cookBook = cookBooks[i];
            row.CreateCell(0).SetCellValue(cookBook.Id);
            row.CreateCell(1).SetCellValue(cookBook.Name);
            row.CreateCell(2).SetCellValue(cookBook.Category ?? "");
            row.CreateCell(3).SetCellValue(cookBook.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
            row.CreateCell(4).SetCellValue(cookBook.UpdatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        
        // 调整列宽
        for (int i = 0; i < 5; i++)
        {
            sheet.AutoSizeColumn(i);
        }
        
        // 写入内存流
        var memoryStream = new MemoryStream();
        workbook.Write(memoryStream, true);
        memoryStream.Position = 0;
        
        return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "菜谱数据.xlsx");
    }
    
    // POST: CookBook/Import
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult ImportFromExcel(IFormFile? file)
    {
        List<CookBook> cookBooks;
        
        if (file == null || file.Length == 0)
        {
            ViewBag.Message = "请选择一个文件";
            ViewBag.IsSuccess = false;
            cookBooks = _context.CookBooks.GetList();
            ViewBag.TotalItems = cookBooks.Count;
            ViewBag.CurrentPage = 1;
            ViewBag.PageSize = 10;
            return View("Index", cookBooks);
        }
        
        try
        {
            var importedCount = 0;
            
            using (var stream = file.OpenReadStream())
            {
                var workbook = new XSSFWorkbook(stream);
                var sheet = workbook.GetSheetAt(0);
                
                // 从第二行开始读取数据（跳过表头）
                for (int row = 1; row <= sheet.LastRowNum; row++)
                {
                    var dataRow = sheet.GetRow(row);
                    if (dataRow == null) continue;
                    
                    // 获取第二列（菜谱名称）作为必须项
                    var nameCell = dataRow.GetCell(1);
                    
                    // 检查菜谱名称是否存在
                    if (nameCell == null || string.IsNullOrWhiteSpace(nameCell.ToString())) continue;
                    
                    var name = nameCell.ToString();
                    
                    // 获取第三列（分类）
                    var categoryCell = dataRow.GetCell(2);
                    var category = categoryCell?.ToString();
                    
                    // 获取第一列（ID）来判断是插入还是更新
                    var idCell = dataRow.GetCell(0);
                    int? id = null;
                    
                    // 尝试解析ID
                    if (idCell != null)
                    {
                        if (idCell.CellType == CellType.Numeric)
                        {
                            id = (int)idCell.NumericCellValue;
                        }
                        else if (idCell.CellType == CellType.String)
                        {
                            int parsedId;
                            if (int.TryParse(idCell.StringCellValue, out parsedId))
                            {
                                id = parsedId;
                            }
                        }
                    }
                    
                    // 解析时间
                    DateTime createdTime = DateTime.Now;
                    DateTime updatedTime = DateTime.Now;
                    
                    // 获取创建时间和更新时间（如果存在）
                    var createdTimeCell = dataRow.GetCell(3);
                    var updatedTimeCell = dataRow.GetCell(4);
                    
                    if (createdTimeCell != null)
                    {
                        if (createdTimeCell.CellType == CellType.Numeric)
                        {
                            var dateValue = createdTimeCell.DateCellValue;
                            if (dateValue.HasValue)
                            {
                                createdTime = dateValue.Value;
                            }
                        }
                        else if (createdTimeCell.CellType == CellType.String)
                        {
                            DateTime parsedCreatedTime;
                            if (DateTime.TryParse(createdTimeCell.StringCellValue, out parsedCreatedTime))
                            {
                                createdTime = parsedCreatedTime;
                            }
                        }
                    }
                    
                    if (updatedTimeCell != null)
                    {
                        if (updatedTimeCell.CellType == CellType.Numeric)
                        {
                            var dateValue = updatedTimeCell.DateCellValue;
                            if (dateValue.HasValue)
                            {
                                updatedTime = dateValue.Value;
                            }
                        }
                        else if (updatedTimeCell.CellType == CellType.String)
                        {
                            DateTime parsedUpdatedTime;
                            if (DateTime.TryParse(updatedTimeCell.StringCellValue, out parsedUpdatedTime))
                            {
                                updatedTime = parsedUpdatedTime;
                            }
                        }
                    }
                    
                    // 如果ID为空，则插入新记录
                    if (!id.HasValue)
                    {
                        // 创建新菜谱
                        var cookBook = new CookBook
                        {
                            Name = name ?? "",
                            Category = category,
                            CreatedTime = createdTime,
                            UpdatedTime = updatedTime
                        };
                        _context.CookBooks.Insert(cookBook);
                    }
                    else
                    {
                        // 检查是否存在相同ID的菜谱
                        var existingCookBook = _context.CookBooks.AsQueryable()
                            .Any(x => x.Id == id.Value);
                        
                        if (existingCookBook)
                        {
                            // 更新现有菜谱
                            var cookBook = _context.CookBooks.AsQueryable()
                                .First(x => x.Id == id.Value);
                            cookBook.Name = name ?? "";
                            cookBook.Category = category;
                            cookBook.UpdatedTime = updatedTime;
                            _context.CookBooks.Update(cookBook);
                        }
                        else
                        {
                            // 使用指定ID创建新菜谱
                            var cookBook = new CookBook
                            {
                                Id = id.Value,
                                Name = name ?? "",
                                Category = category,
                                CreatedTime = createdTime,
                                UpdatedTime = updatedTime
                            };
                            _context.CookBooks.Insert(cookBook);
                        }
                    }
                    
                    importedCount++;
                }
            }
            
            ViewBag.Message = $"成功导入 {importedCount} 条菜谱数据";
            ViewBag.IsSuccess = true;
        }
        catch (Exception ex)
        {
            ViewBag.Message = "导入失败: " + ex.Message;
            ViewBag.IsSuccess = false;
        }
        
        cookBooks = _context.CookBooks.GetList();
        ViewBag.TotalItems = cookBooks.Count;
        ViewBag.CurrentPage = 1;
        ViewBag.PageSize = 10;
        return View("Index", cookBooks);
    }
}